#！/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time     :2019/1/13 17:10
# @Author   :Yosef-夜雨声烦
# E-mail    :wurz529@foxmail.com
# File      :http_request.py
# Software  :PyCharm Community Edition
import requests
from common.mylog import Mylog

logger = Mylog("http_requests")


class HttpRequests:
    def __init__(self, url, params, headers=None, json=None):
        self.url = url
        self.params = params
        self.headers = headers
        self.json = json

    def http_requests(self, method, cookies=None):

        if method.upper() == "GET":
            try:
                res = requests.get(self.url, self.params, headers=self.headers, cookies=cookies)
                logger.info("url:{}的get请求执行成功".format(self.url))
            except Exception as e:
                logger.info("执行get请求报错，报错信息是{}".format(e))


        elif method.upper() == "POST":
            try:
                res = requests.post(self.url, data=self.params, json=self.json, cookies=cookies)
                logger.info("url:{}的post请求执行成功".format(self.url))
            except Exception as e:
                logger.info("执行post请求报错，报错信息是{}".format(e))


        else:
            logger.info("请求方式不正确，请检查请求方式是否是get或者post")
            res = "Error:{}请求方式不正确".format(method)

        return res


if __name__ == "__main__":
    url = "http://api.shujuzhihui.cn/api/joke/qiubai/word"
    appkey = "xxxxxx"  # appkey请自己注册获取
    params = {"appKey": appkey, "page": 1}
    headers = {"User-Agent": "Mozilla/5.0"}
    json = {"User-Agent": "Mozilla/5.0"}
    res1 = HttpRequests(url, params, headers=headers).http_requests("get")
    res2 = HttpRequests(url, params, json=json).http_requests("post")
    print(res1.json()["ERRORCODE"])
    print(res2.json()["ERRORCODE"])
